package com.hzncc.flowable_diboot.controller.customer;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.core.entity.Dictionary;
import com.diboot.core.service.DictionaryService;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.LabelValue;
import com.diboot.core.vo.Pagination;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.util.IamSecurityUtils;
import com.diboot.tenant.entity.IamTenant;
import com.diboot.tenant.service.IamTenantService;
import com.hzncc.flowable_diboot.dto.SapCustomerDTO;
import com.hzncc.flowable_diboot.entity.SalesGroupContent;
import com.hzncc.flowable_diboot.entity.SapCustomer;
import com.hzncc.flowable_diboot.service.SalesGroupContentService;
import com.hzncc.flowable_diboot.service.SapCustomerService;
import com.hzncc.flowable_diboot.util.ConstantUtil;
import com.hzncc.flowable_diboot.vo.SapCustomerDetailVO;
import com.hzncc.flowable_diboot.vo.SapCustomerEditVO;
import com.hzncc.flowable_diboot.vo.SapCustomerListVO;
import com.sap.conn.jco.JCoException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * SAP客户 相关rest接口
 *
 * @author MyName
 * @version 1.0
 * @date 2024-05-27
 * Copyright © MyCorp
 */
@Slf4j
@RequestMapping("/sap-customer")
@BindPermission(name = "SAP客户")
@RestController
public class SapCustomerController extends BaseCrudRestController<SapCustomer> {

    @Autowired
    private SapCustomerService sapCustomerService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private IamTenantService iamTenantService;

    @Autowired
    private SalesGroupContentService salesGroupContentService;

    /**
     * 查询资源对象的列表VO记录
     * <p>
     * url请求参数示例: ?fieldA=abc&pageSize=20&pageIndex=1&orderBy=id
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping()
    public JsonResult<List<SapCustomerListVO>> getListVOMapping(SapCustomerDTO queryDto, Pagination pagination) throws Exception {
        return super.getViewObjectList(queryDto, pagination, SapCustomerListVO.class);
    }

    /**
     * 根据id查询资源对象的详情VO
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult<SapCustomerDetailVO> getDetailVOMapping(@PathVariable("id") String id) throws Exception {
        SapCustomerDetailVO detailVO = sapCustomerService.getViewObject(id, SapCustomerDetailVO.class);
        return JsonResult.OK(detailVO);
    }


    /**
     * 创建资源对象数据
     *
     * @param sapCustomer
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping()
    public JsonResult<?> createModelMapping(@RequestBody SapCustomer sapCustomer) throws Exception {
        boolean success = sapCustomerService.createEntity(sapCustomer);
        log.debug("新建数据 SAP客户:{} {}", sapCustomer.getId(), success ? "成功" : "失败");
        return JsonResult.OK(sapCustomer.getId());
    }

    /**
     * 批量创建资源对象数据
     *
     * @param sapCustomerList
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch")
    public JsonResult<?> batchCreateModelMapping(@RequestBody List<SapCustomer> sapCustomerList) throws Exception {
        boolean success = sapCustomerService.createEntities(sapCustomerList);
        log.debug("批量新建数据 SAP客户 {}", success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据id更新资源对象
     *
     * @param sapCustomer
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateModelMapping(@PathVariable("id") String id, @RequestBody SapCustomer sapCustomer) throws Exception {
        boolean success = sapCustomerService.updateEntity(sapCustomer);
        log.debug("更新数据 SAP客户:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteModelMapping(@PathVariable("id") String id) throws Exception {
        boolean success = sapCustomerService.deleteEntity(id);
        log.debug("删除数据 SAP客户:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据ids集合删除资源对象
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch-delete")
    public JsonResult<?> deleteEntityMapping(@RequestBody List<String> ids) throws Exception {
        boolean success = sapCustomerService.deleteEntities(ids);
        log.debug("批量删除数据 SAP客户:{} {}", ids, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }


    /**
     * 创建sap客户
     *
     * @param param 参数
     * @return
     * @author 陈广煜
     * @date 2024/5/28
     */
    @Log(operation = OperationCons.LABEL_WRITE)
    @BindPermission(name = OperationCons.LABEL_WRITE, code = OperationCons.CODE_WRITE)
    @PostMapping("/createSap")
    public JsonResult<?> createSapCustomer(@RequestBody Map<String, Object> param) throws JCoException {
        String res = sapCustomerService.createSapCustomer(param);
        if (res.startsWith("E")) {
            return JsonResult.FAIL_EXCEPTION(res.replaceAll("检索项", "客户简称"));
        }
        return JsonResult.OK();
    }

    /**
     * 获取省份
     *
     * @return
     * @author 陈广煜
     * @date 2024/5/30
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/province")
    public JsonResult<?> getProvince(@RequestParam String code) {
        QueryWrapper<Dictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(Dictionary::getItemName, Dictionary::getItemValue);
        queryWrapper.eq("type", ConstantUtil.DIC_TYPE_PROVINCE).and(e -> e.eq("description", code));
        List<LabelValue> labelValueList = dictionaryService.getLabelValueList(queryWrapper);
        return JsonResult.OK(labelValueList);
    }

    /**
     * 查询销售部门
     *
     * @param code 销售组织
     * @return
     * @author 陈广煜
     * @date 2024/6/26
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/dept")
    public JsonResult<?> getSalesDept(@RequestParam String code) {
        QueryWrapper<Dictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(Dictionary::getItemName, Dictionary::getItemValue);
        queryWrapper.eq("type", ConstantUtil.DIC_TYPE_DEPT).and(e -> e.like("description", code));
        List<LabelValue> labelValueList = dictionaryService.getLabelValueList(queryWrapper);
        return JsonResult.OK(labelValueList);
    }

    /**
     * 获取当前用户公司编码
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/4
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/companyCode")
    public JsonResult<?> getCompanyCode() {
        String currentTenantId = IamSecurityUtils.getCurrentTenantId();
        IamTenant tenant = iamTenantService.getEntity(currentTenantId);
        return JsonResult.OK(tenant.getOaNum());
    }

    /**
     * 获取当前用户公司编码
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/4
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/orgId")
    public JsonResult<?> getOrgId() {
        String currentTenantId = IamSecurityUtils.getCurrentTenantId();
        IamTenant tenant = iamTenantService.getEntity(currentTenantId);
        String orgId = tenant.getOrgId();
        if (StringUtils.isNoneBlank(orgId)){
            String[] orgIds = orgId.split(",");
            return JsonResult.OK(orgIds);
        }
        return JsonResult.OK();
    }

    /**
     * 根据sap客户编号查询资源对象的详情VO
     *
     * @param sapNo sap客户编号
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/sapNo")
    public JsonResult<SapCustomerDetailVO> getDetailVOMappingByCode(@RequestParam String sapNo) throws Exception {
        QueryWrapper<SapCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sap_no",sapNo);
        SapCustomerDetailVO detailVO = sapCustomerService.getViewObject(queryWrapper, SapCustomerDetailVO.class);
        return JsonResult.OK(detailVO);
    }

    /**
     * sap客户编辑反查
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/5
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/editInput")
    public JsonResult<?> getEditSap(@RequestParam String sapNo){
        if (StringUtils.isBlank(sapNo)){
            return JsonResult.WARN_PERFORMANCE_ISSUE("SAP客户编码为空");
        }
        QueryWrapper<SapCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sap_no",sapNo);
        SapCustomerDetailVO detailVO = sapCustomerService.getViewObject(queryWrapper, SapCustomerDetailVO.class);
        if (detailVO == null){
            return JsonResult.FAIL_EXCEPTION("SAP客户不存在");
        }
        SapCustomerEditVO editVO = new SapCustomerEditVO();
        editVO.setCustomer(detailVO);
        QueryWrapper<SalesGroupContent> qw = new QueryWrapper<>();
        qw.eq("sap_customer_id",detailVO.getId());
        List<SalesGroupContent> entityList = salesGroupContentService.getEntityList(qw);
        editVO.setSalesGroups(entityList);
        return JsonResult.OK(editVO);
    }

    /**
     * 查询相同公司代码下的SAP客户
     * @param customerName 客户名称
     * @return
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/searchExistSapCustomer")
    public JsonResult<SapCustomerEditVO> getSameCompanySapCustomer(@RequestParam String customerName){
        return JsonResult.OK(sapCustomerService.getSameCompanySapCustomer(customerName));
    }
}